﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using ERP_RORZE_SYSTEM;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ERP_RORZE_DLL.Business
{
    public partial class frm_Add_PurchaseOrder : Form
    {
        public frm_Add_PurchaseOrder()
        {
            InitializeComponent();
            this.mySetting = new INISettings();
            this.myConnection = new SqlConnection(mySetting.SQLConnectionString);
            this.newPOID = "";
            InitialPOID();
            this.inputDate.Text = DateTime.Now.ToShortDateString();
            getSupplierList();
            this.supplierID.Properties.AutoComplete = true;
            //this.supplierID.SelectedIndex = 0;
            this.commodityName.Text = "Parts for RORZE ROBOTECH CO., LTD.";
            getDeliveryList();
            this.deliveryID.Properties.AutoComplete = true;
            //this.deliveryID.SelectedIndex = 0;
            getShipToList();
            this.shiptoID.Properties.AutoComplete = true;
            //this.shiptoID.SelectedIndex = 0;
            getPaymentList();
            this.paymentID.Properties.AutoComplete = true;
            //this.paymentID.SelectedIndex = 0;
        }

        ////////////////////////////////////////////////
        /// Initial new PO information to form
        ////////////////////////////////////////////////        
        private void InitialPOID()
        {
            int new_id_number = 0;
            string new_id_string = "";
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT MAX(SUBSTRING(ID, 12, 4))  FROM \"241_PO\"";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    new_id_number = Int32.Parse(dataReader[0].ToString());
                }
                new_id_number++;
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
                DateTime in_Date = DateTime.Now;
                new_id_string = in_Date.Year.ToString().Substring(2) + in_Date.Month.ToString("D2") + in_Date.Day.ToString("D2");
                new_id_string = "/" + new_id_string + "/" + new_id_number.ToString("D4") + "-00";                                
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot create new PO ID");
                this.Dispose();
            }
            this.poNo.Text = new_id_string;                        
        }
        
        ////////////////////////////////////////////////
        /// Load Supplier list to form
        ////////////////////////////////////////////////
        private void getSupplierList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT SupplierID, SupplierName FROM \"222_Supplier\" ORDER BY SupplierName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["SupplierName"].ToString();
                    item.Value = dataReader["SupplierID"].ToString();
                    this.supplierID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Supplier list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Delivery list to form
        ////////////////////////////////////////////////
        private void getDeliveryList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT DeliveryTermID, DeliveryTermName FROM \"222_DeliveryTerm\" ORDER BY DeliveryTermName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["DeliveryTermName"].ToString();
                    item.Value = dataReader["DeliveryTermID"].ToString();
                    this.deliveryID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Delivery list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Ship To list to form
        ////////////////////////////////////////////////
        private void getShipToList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ShipToCode, ShipToName FROM \"222_ShipTo\" ORDER BY ShipToName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["ShipToName"].ToString();
                    item.Value = dataReader["ShipToCode"].ToString();
                    this.shiptoID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Ship To list");
            }
        }

        ////////////////////////////////////////////////
        /// Load Ship To list to form
        ////////////////////////////////////////////////
        private void getPaymentList()
        {
            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT PaymentID, PaymentName FROM \"222_Payment\" ORDER BY PaymentName";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                while (dataReader.Read())
                {
                    ComboboxItem item = new ComboboxItem();
                    item.Text = dataReader["PaymentName"].ToString();
                    item.Value = dataReader["PaymentID"].ToString();
                    this.paymentID.Properties.Items.Add(item);
                }
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot get Payment list");
            }
        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            bool conflict = false;

            if (this.prefixID.Text == "")
            {
                this.newPOID = "000" + this.poNo.Text;
            }
            else
            {
                int pre = Int32.Parse(this.prefixID.Text);
                this.newPOID = pre.ToString("D3") + this.poNo.Text;
            }

            try
            {
                myConnection.Open();
                SqlCommand cmd_sql = myConnection.CreateCommand();
                cmd_sql.CommandText = "SELECT ID  FROM \"241_PO\" WHERE ID='" + this.newPOID + "'";
                SqlDataReader dataReader = cmd_sql.ExecuteReader();
                if (dataReader.Read())
                {
                    conflict = true;
                }                
                dataReader.Close();
                cmd_sql.Dispose();
                myConnection.Close();                
            }
            catch
            {
                if (myConnection.State == ConnectionState.Open)
                {
                    myConnection.Close();
                }
                MessageBox.Show("Cannot check PO ID. Please try again.");                
            }

            if (conflict)
            {
                MessageBox.Show("POID has been conflicted. Please try again.");
                InitialPOID();
            }
            else
            {
                ComboboxItem supllier = (ComboboxItem)supplierID.SelectedItem;
                ComboboxItem delivery = (ComboboxItem)deliveryID.SelectedItem;
                ComboboxItem payment = (ComboboxItem)paymentID.SelectedItem;
                ComboboxItem shipto = (ComboboxItem)shiptoID.SelectedItem;
                try
                {
                    DateTime inputdate;                    
                    DateTime.TryParse(inputDate.DateTime.Date.ToString(), out inputdate);
                    myConnection.Open();
                    string sql = "INSERT INTO \"241_PO\""
                        + " (ID, InputDate, SupplierID, NameOfCommodity, DeliveryTermID, PaymentID, Remark, ShipToCode)"
                        + " VALUES ('" + newPOID + "', @inputdate, '" + supllier.Value + "', '" + commodityName.Text + "',"
                        + " '" + delivery.Value + "', '" + payment.Value + "', '" + remarkText.Text + "', '" + shipto.Value + "')";
                    SqlCommand cmd_sql = new SqlCommand(sql, myConnection);
                    cmd_sql.Parameters.Add("@inputdate", SqlDbType.DateTime).Value = inputdate.Date;
                    cmd_sql.ExecuteNonQuery();
                    cmd_sql.Dispose();
                    myConnection.Close();
                    MessageBox.Show("Purchase Order added success!");
                    //this.Dispose();
                    clearForm();
                }
                catch
                {
                    if (myConnection.State == ConnectionState.Open)
                    {
                        myConnection.Close();
                    }
                    MessageBox.Show("Cannot add Purchase Order. Plase try again.");
                }
            }
        }

        private void clearForm()
        {
            foreach (Control c in this.Controls)
            {
                if (c is DevExpress.XtraEditors.TextEdit)
                {
                    ((DevExpress.XtraEditors.TextEdit)c).Text = null;
                }

                if (c is DevExpress.XtraEditors.ComboBoxEdit)
                {
                    ((DevExpress.XtraEditors.ComboBoxEdit)c).SelectedIndex = -1;
                }

                if (c is System.Windows.Forms.MaskedTextBox)
                {
                    ((System.Windows.Forms.MaskedTextBox)c).Text = null;
                }
            }
        }
    }   
}
